package com.ykq.service.impl;

import com.ykq.entity.Menu;
import com.ykq.entity.Staff;
import com.ykq.mapper.MenuMapper;
import com.ykq.service.MenuService;
import com.ykq.vo.R;
import com.ykq.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 8:55 2024/10/22
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private HttpSession session;
    @Override
    public R findByStaffId() {
        Staff staff = (Staff) session.getAttribute("staff");//获取当前用户信息
        Integer staffid = staff.getStaffid();//获取当前用户id
        List<Menu> menus = menuMapper.selectByStaffId(staffid);//根据当前用户id查询菜单
        //找到一级菜单 。mpid=0
        List<Menu> firstMenus=new ArrayList<>();
        for(Menu m:menus){
            if(m.getMpid()==0){//一级菜单
                firstMenus.add(m);//添加一级菜单到容器中
            }
        }
        //遍历一级菜单，找到二级菜单
        for(Menu first:firstMenus){
            List<Menu> children=new ArrayList<>();//创建二级菜单容器
            //遍历所有菜单
            for(Menu m:menus){
                if(m.getMpid().equals(first.getMid())){
                    children.add(m);
                }
            }
            //将二级菜单添加到一级菜单中
            first.setChildren(children);
        }

        return R.ok(firstMenus);
    }

    @Override
    public R listByRoleId(Integer roleId) {
        //查询所有的菜单。
        List<Menu> menus = menuMapper.selectAll();
        //查询一级菜单
        List<Menu> firstMenus=new ArrayList<>();
        for(Menu m:menus){
            if(m.getMpid()==0){//一级菜单
                firstMenus.add(m);//添加一级菜单到容器中
            }
        }
        //遍历一级菜单，找到二级菜单
        for(Menu first:firstMenus){
            List<Menu> children=new ArrayList<>();//创建二级菜单容器
            //遍历所有菜单
            for(Menu m:menus){
                if(m.getMpid().equals(first.getMid())){
                    children.add(m);
                }
            }
            //将二级菜单添加到一级菜单中
            first.setChildren(children);
        }

        //2.根据角色id查询菜单id
        List<Integer> menuIds = menuMapper.selectByRoleId(roleId);

        //vo或map
//        TreeVo treeVo=new TreeVo(firstMenus,menuIds);
        Map<String,Object> map=new HashMap<>();
        map.put("k1",firstMenus);
        map.put("k2",menuIds);
        return R.ok(map);
    }

    @Override
    public R confirm(Integer roleid, Integer[] checkKeys) {
        //1.根据角色id删除对应的菜单id.--rolememu
        int row= menuMapper.deleteByRoleId(roleid);
        //2.添加---
        for(Integer key:checkKeys){
            menuMapper.insert01(roleid,key);
        }
        return R.ok();
    }
}




























